<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryForm" size="default" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable size="default"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="创建时间" prop="createdTime">
        <el-date-picker
          v-model="time"
          type="datetimerange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          editable
          :default-time="defaultTime1"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="default" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="default" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain :icon="Edit" size="default" @click="handleAdd(mark)">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain :icon="Delete" size="default" :disabled="multiple"
          @click="handleDelete">删除</el-button>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <div style="overflow: auto">
      <el-table v-loading="loading" :data="adminList" @selection-change="handleSelectionChange" style="width: 100%">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="用户id" align="center" prop="id" />
        <el-table-column label="用户名" align="center" prop="username" />
        <el-table-column label="身份证后6位" align="center" prop="idCard" />
        <el-table-column label="年龄" align="center" prop="age" />
        <el-table-column label="电话号码" align="center" prop="phone" />
        <el-table-column label="用户状态" align="center" prop="status" >
          <template #default="{ row }">
            {{ row.status == 0 ? '启用' : '禁用' }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createdTime" width="180"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
          <template #default="scope">
            <el-button size="small" type="success" plain :icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button size="small" type="danger" plain :icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <el-pagination
      v-show="total > 0"
      :total="total"
      background
      :page-sizes="[10, 20, 30, 40]"
      layout=" prev, pager, next, sizes,->, jumper,total"
      :current-page="queryParams.pageNo"
      :page-size="queryParams.pageSize"
      @current-change="handlePageChange"
      @size-change="handleSizeChange"
      class="custom-pagination"
    />
    
    <!-- 添加或修改管理员对话框 -->
      <el-dialog v-model="open" :title="title" width="500px" append-to-body>
        <el-form ref="dialogForm" :model="form" :rules="rules" label-width="80px">
          <el-form-item label-width="120"  label="用户名" prop="username">
            <el-input v-model="form.username" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label-width="120" label="身份证后6位" prop="idCard">
            <el-input v-model="form.idCard" placeholder="请输入身份证后6位" />
          </el-form-item>
          <el-form-item  label-width="120" label="年龄" prop="age">
            <el-input v-model="form.age" placeholder="请输入年龄" />
          </el-form-item>
          <el-form-item  label-width="120" label="状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择状态">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item  label-width="120" label="电话号码" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入电话号码" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted ,toRef} from 'vue';
import dayjs from 'dayjs';
import { watchEffect  } from 'vue';
import $store from '@/vuex/store';
import { Edit, Delete } from '@element-plus/icons-vue';
import {
  listAdmin,
  getAdmin,
  delAdmin,
  addAdmin,
  updateAdmin,
} from "@/api/admin";
import { ElMessage,ElMessageBox } from 'element-plus';
import { useRoute ,useRouter} from 'vue-router';
const loading = ref(true);
const ids = ref([]);
const $router = useRouter();
const $route = useRoute();
let mark = ref(0);
const time = ref('');
const defaultTime1 = new Date(2024, 6, 12, 0, 0, 0) // '12:00:00'
const single = ref(true);
const multiple = ref(true);
const showSearch = ref(true);
const total = ref(0);
const adminList = ref([]);
const title = ref("");
const open = ref(false);
const dialogForm = ref(null);
const options = ref([
      { value: 0, label: '启用' },
      { value: 1, label: '禁用' },
    ]);
const statusText = ref('启用');
watchEffect(
      (newStatus) => {
        statusText.value = newStatus === 0 ? '启用' : '禁用';
      },
    );
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  username: null,
  statTime: null,
  endTime: null,
});

const form = ref({
  id: null,
  username: null,
  password: null,
  idCard: null,
  age: null,
  phone: null,
  status: null,
  createdTime: null,
  updateTime: null,
});
//校验年龄
const validateAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('年龄不能为空'));
      }
      if (isNaN(value)) {
        return callback(new Error('年龄必须为数字'));
      }
      if (value < 0 || value > 100) {
        return callback(new Error('请输入0到100之间的年龄'));
      }
      callback();
    };
const rules = {
  username: [
    { required: true, message: "用户名不能为空", trigger: "blur" },
  ],
  idCard: [
    { required: true, message: "身份证后号码不能为空", trigger: "blur" },
    { min: 6, max: 6, message: "身份证长度为6位", trigger: "blur" },
  ],
  age: [
        { required: true, message: '年龄不能为空', trigger: 'blur' },
        { validator: validateAge, trigger: 'blur' }
      ],
  phone: [
    { required: true, message: "电话号码不能为空", trigger: "blur" },
    { min:11 ,max:11, message: "电话号码长度为11位", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "电话号码格式错误", trigger: "blur" }
  ],
  status: [
    { required: true, message: "用户状态不能为空", trigger: "change" },
  ],
};

const reset = () => {
  Object.assign(form.value, {
    id: null,
    username: null,
    password: null,
    idCard: null,
    age: null,
    phone: null,
    status: null,
    createdTime: null,
    updateTime: null,
  });
};

const getList = () => {
  loading.value = true;
  listAdmin(queryParams).then((response) => {
    if (response.code === 200) {
      adminList.value = response.data.lists;
      total.value = response.data.total;
    } else {
      ElMessage.error("数据加载失败");
    }
    loading.value = false;
  }).catch(() => {
    ElMessage.error("数据加载异常")
    loading.value = false;
  });
};

const cancel = () => {
  open.value = false;
  reset();
};

const handleQuery = () => {
  //  queryParams.statTime = time.value[0];
  //  queryParams.endTime = time.value[1];
  queryParams.statTime = dayjs(time.value[0]).format('YYYY-MM-DD HH:mm:ss');
  queryParams.endTime = dayjs(time.value[1]).format('YYYY-MM-DD HH:mm:ss');
  // console.log(queryParams.statTime)
  // console.log(queryParams.endTime)
  queryParams.pageNo = 1;
  getList();
};

const resetQuery = () => {
  handleQuery();
};

const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

const handleAdd = () => {
  reset();
  mark.value = 1;
  console.log(form.value)
  open.value = true;
  title.value = "添加管理员";
};

const handleUpdate = (row) => {
  reset();
  const adminId = row.id;
  getAdmin(adminId).then((response) => {
    form.password = ""; // 清空密码字段
    form.value = response.data
    open.value = true;
    title.value = "修改管理员";
  });
};

const handleDelete = (row) => {
  const adminId = row.id || ids.value;
  ElMessageBox.confirm(
        `是否确认删除管理员编号为 "${adminId}" 的数据项？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
    .then(() => {
      return delAdmin(adminId);
    })
    .then(() => {
      getList();
      ElMessage({
        type: "success",
        message: "删除成功!",
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};

const submitForm = () => {
  dialogForm.value.validate((valid) => {
    if (valid) {
      if (form.value.id && mark.value != 1) {
        console.log(1111)
        updateAdmin(form.value).then((res) =>  {
          if(res.code === 200){
            // 提示消息
            console.log(res.data)
            ElMessage({
              type: 'success',
              message: res.message
            })
            //如果当前登录的管理员的状态改为禁用就退出登录
            if(form.value.username == localStorage.getItem('username') && form.value.status == 1){
              open.value = false;
              setTimeout(()=>{
                ElMessage({
                  type: 'error', 
                  message: "账号被禁用，退出到登录",
                })
              },3000)
              //清理本地缓存
              localStorage.clear;
              $store.commit('REMOVE');
              $router.push("/login");
              return;
            } 
          }
          else ElMessage.error(res.message)
          open.value = false;
          getList();
        });
      } else {
        addAdmin(form.value).then((res) => {
          mark.value = 0;
          // 提示消息
          ElMessage({
            type: 'success',
            message: res.message
          })
          open.value = false;
          getList();
        });
      }
    }
  });
};

// 处理页码变化
const handlePageChange = (newPage) => {
  console.log(newPage)
  queryParams.pageNo = newPage;
  getList();
};

// 处理页大小变化
const handleSizeChange = (newSize) => {
  queryParams.pageSize = newSize;
  queryParams.pageNo = 1; // 重置页码为1
  getList();
};
onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss">
.admin-table {
  width: 100%;
  border-collapse: collapse;
}
.admin-dialog{
  z-index: 9000;
}
.el-pagination{
  margin: 30px 0;
  margin-right: 30px;
}
.admin-table th,
.admin-table td {
  border: 1px solid #ebeef5;
  padding: 8px;
  text-align: center;
}

.admin-table th {
  background-color: #f5f7fa;
}
.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>
